package tech.waterism.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import cn.hutool.core.io.resource.ResourceUtil;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;

/**
 * JSON文件修复工具
 * 1. DHF和SMS_3: 重命名timeSeries为rainfallSeries
 * 2. LAG: 修复字符串数字，重构时间序列结构
 */
public class JsonFixer {

    public static void main(String[] args) throws IOException {
        String basePath = "hydro-model-core/src/main/resources/json/";
        
        System.out.println("=".repeat(60));
        System.out.println("🔧 修复模型JSON文件");
        System.out.println("=".repeat(60));
        
        // 1. 修复DHF-input.json
        System.out.println("\n📝 处理 DHF-input.json...");
        fixDHF(basePath + "DHF-input.json");
        
        // 2. 修复SMS_3-input.json
        System.out.println("\n📝 处理 SMS_3-input.json...");
        fixSMS3(basePath + "SMS_3-input.json");
        
        // 3. 修复LAG-input.json
        System.out.println("\n📝 处理 LAG-input.json...");
        fixLAG(basePath + "LAG-input.json");
        
        System.out.println("\n" + "=".repeat(60));
        System.out.println("✅ 所有JSON文件已处理完成");
        System.out.println("=".repeat(60));
    }

    /**
     * 修复DHF-input.json：重命名timeSeries为rainfallSeries
     */
    private static void fixDHF(String filePath) throws IOException {
        String content = ResourceUtil.readUtf8Str("json/DHF-input.json");
        JSONObject data = JSON.parseObject(content);
        
        // 重命名timeSeries为rainfallSeries
        if (data.containsKey("timeSeries")) {
            JSONArray timeSeries = data.getJSONArray("timeSeries");
            data.remove("timeSeries");
            data.put("rainfallSeries", timeSeries);
            System.out.println("  ✅ 重命名 timeSeries → rainfallSeries: " + timeSeries.size() + " 条记录");
        }
        
        // 写入文件
        writeJson(filePath, data);
    }

    /**
     * 修复SMS_3-input.json：重命名timeSeries为rainfallSeries
     */
    private static void fixSMS3(String filePath) throws IOException {
        String content = ResourceUtil.readUtf8Str("json/SMS_3-input.json");
        JSONObject data = JSON.parseObject(content);
        
        // 重命名timeSeries为rainfallSeries
        if (data.containsKey("timeSeries")) {
            JSONArray timeSeries = data.getJSONArray("timeSeries");
            data.remove("timeSeries");
            data.put("rainfallSeries", timeSeries);
            System.out.println("  ✅ 重命名 timeSeries → rainfallSeries: " + timeSeries.size() + " 条记录");
        }
        
        // 写入文件
        writeJson(filePath, data);
    }

    /**
     * 修复LAG-input.json：修复字符串数字，重构时间序列结构
     */
    private static void fixLAG(String filePath) throws IOException {
        String content = ResourceUtil.readUtf8Str("json/LAG-input.json");
        JSONObject data = JSON.parseObject(content);
        
        // 1. 修复字符串形式的数字字段
        int fixed = 0;
        for (Map.Entry<String, Object> entry : new HashSet<>(data.entrySet())) {
            String key = entry.getKey();
            Object value = entry.getValue();
            
            if (value instanceof String && !key.equals("start") && !key.equals("end")) {
                try {
                    String strValue = (String) value;
                    if (strValue.contains(".")) {
                        data.put(key, Double.parseDouble(strValue));
                        fixed++;
                    } else {
                        data.put(key, Integer.parseInt(strValue));
                        fixed++;
                    }
                } catch (NumberFormatException e) {
                    // 不是数字，跳过
                }
            }
        }
        if (fixed > 0) {
            System.out.println("  ✅ 共修复 " + fixed + " 个字符串数字字段");
        }
        
        // 2. 重构时间序列结构：dt + rain + runoffSim + rSim → flowSeries
        if (data.containsKey("dt")) {
            JSONArray dt = data.getJSONArray("dt");
            JSONArray rain = data.getJSONArray("rain");
            JSONArray runoffSim = data.getJSONArray("runoffSim");
            JSONArray rSim = data.getJSONArray("rSim");
            
            JSONArray flowSeries = new JSONArray();
            
            for (int i = 0; i < dt.size(); i++) {
                JSONObject point = new JSONObject();
                point.put("time", dt.getString(i));
                
                if (rain != null && i < rain.size()) {
                    point.put("rain", rain.getDoubleValue(i));
                }
                
                if (runoffSim != null && i < runoffSim.size()) {
                    point.put("runoff", runoffSim.getDoubleValue(i));
                }
                
                // rSim是二维数组，转换为每个时间点的rSim数组 (三水源: RS, RI, RG)
                if (rSim != null && rSim.size() > 0) {
                    JSONArray rSimValues = new JSONArray();
                    for (int j = 0; j < rSim.size(); j++) {
                        JSONArray row = rSim.getJSONArray(j);
                        if (i < row.size()) {
                            rSimValues.add(row.getDoubleValue(i));
                        }
                    }
                    if (!rSimValues.isEmpty()) {
                        point.put("rSim", rSimValues);
                    }
                }
                
                flowSeries.add(point);
            }
            
            // 移除旧字段
            data.remove("dt");
            data.remove("rain");
            data.remove("runoffSim");
            data.remove("rSim");
            
            // 添加新字段
            data.put("flowSeries", flowSeries);
            
            System.out.println("  ✅ 重构时间序列: dt + rain + runoffSim + rSim → flowSeries (包含 rSim 三水源): " + flowSeries.size() + " 条记录");
            
            // 示例输出
            System.out.println("  📊 示例数据（前3条）:");
            for (int i = 0; i < Math.min(3, flowSeries.size()); i++) {
                System.out.println("     [" + i + "] " + flowSeries.getJSONObject(i).toJSONString());
            }
        }
        
        // 写入文件
        writeJson(filePath, data);
    }

    /**
     * 写入JSON文件
     */
    private static void writeJson(String filePath, JSONObject data) throws IOException {
        File file = new File(filePath);
        try (FileWriter writer = new FileWriter(file)) {
            writer.write(JSON.toJSONString(data, true));
        }
        System.out.println("  ✅ 文件已更新: " + file.getAbsolutePath());
    }
}

